<template>
  <div>
    <el-card>
      <template #header>
        <span class="title">用户总数 {{ createdCount }}，活跃用户 {{ activeCount }}</span>
      </template>
      <el-row>
        <el-col :span="12">
          <v-chart style="height: 500px" :option="lineOption" :theme="isDark ? 'dark' : ''" autoresize />
        </el-col>
        <el-col :span="12">
          <v-chart style="height: 500px" :option="pieOption" :theme="isDark ? 'dark' : ''" autoresize />
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { getCount, getMonthlyCount } from '@/service/user'
import { useGlobalStore } from '@/stores/global'
// import { ECharts } from 'echarts'

const global = useGlobalStore()
const isDark = computed(() => global.isDark)
const createdCount = ref(0)
const activeCount = ref(0)
const lineOption = ref()
const pieOption = ref()

onMounted(async () => {
  const { count, active } = await getCount()
  createdCount.value = count
  activeCount.value = active
  pieOption.value = parsePieOpt(count, active)

  const rawData = await getMonthlyCount()
  lineOption.value = parseCreatedChartData(rawData)
})

function parseCreatedChartData(data: any[]) {
  const xArr = data.map(item => item.month)
  const seriesArr = data.map(item => item.count)

  return {
    title: {
      text: '每月新增用户',
      top: 10,
      left: 'center'
    },
    tooltip: {},
    grid: {
      top: 140,
      bottom: 40
    },
    xAxis: {
      type: 'category',
      data: xArr
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '新增用户',
        type: 'line',
        data: seriesArr
      }
    ]
  }
}

function parsePieOpt(count = 0, active = 0) {
  return {
    title: {
      text: '活跃用户占比',
      top: 10,
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '10%',
      data: ['非活跃', '活跃']
    },
    series: [
      {
        type: 'pie',
        radius: '65%',
        center: ['50%', '60%'],
        data: [
          { value: active, name: '活跃' },
          { value: count - active, name: '非活跃' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
}
</script>
<style lang="scss" scoped></style>
